#!/bin/bash

# 定义上传至 S3 兼容存储的函数
upload_to_oss() {
  local source_path="$FILE_PATH"
  local dest_bucket="s3://$OSS_BUCKET_NAME"
  local dest_object="$TARGET_PATH"

  echo "Uploading to CMC S3 OSS..."
  # 使用 s3cmd 上传文件
  #  s3cmd -c ./jenkins/s3cfg put "$source_path" "$dest_bucket/$dest_object" || {
  #    echo >&2 "ERROR: Failed to upload to S3 storage."
  #    exit 1
  #  }
  echo "Uploaded to CMC S3 OSS successfully"

  # 保存上传后的完整路径
  UPLOADED_PATH="$dest_bucket/$dest_object"
  echo "Uploaded file path: $UPLOADED_PATH"

  local expireDatetime=$(date -v+365d +"%Y-%m-%d %H:%M:%S")
  echo "【下载链接】有效期365天, 过期时间：$expireDatetime"

  # 生成签名 URL
  #  SIGNED_URL=$(s3cmd -c ./jenkins/s3cfg signurl "$UPLOADED_PATH" $(date -v+365d +%s))
  #  echo "$SIGNED_URL"
}

get_sign_url(){
  source .venv/bin/activate
  python ${WORKSPACE}/jenkins/signurl.py $OSS_AK $OSS_SK $OSS_END_POINT $OSS_REGION $OSS_BUCKET_NAME "${TARGET_PATH}"

}

# 通用的 POST 请求方法，返回 body 和 status
http_post_with_curl() {
  local url="$1"
  local token="$2"
  local payload="$3"

  # 发送 POST 请求，响应体+状态码
  local response
  response=$(curl -s -w "\n%{http_code}" -H "token: $token" -H "content-type: application/json" -d "$payload" "$url")

  # 只返回 body，不输出状态码
  local body
  body=$(printf "%s" "$response" | sed '$d')
  local http_status
  http_status=$(printf "%s" "$response" | tail -n 1)
  # 检查 http_status 是否为数字且为 3 位数
  if [[ ! "$http_status" =~ ^[0-9]{3}$ ]]; then
    echo "WARN: http_post_with_curl 状态码异常: $http_status" >&2
    return 1
  fi
  echo "$body"
  return $http_status
}

upToOTA() {
  # 检查必要变量
  if [[ -z "$API_URL" || -z "$TOKEN" || -z "$OTA_APP_NAME" || -z "$APP_VERSION" || -z "$APP_BUILD_NUM" || -z "$OSS_BUCKET_NAME" || -z "$TARGET_PATH" ]]; then
    echo "ERROR: 缺少必要参数，无法上传OTA。" >&2
    return 1
  fi

  local payload
  payload=$(
    cat <<EOF
{
  "versionCategory": "app",
  "isApprove": true,
  "versionType": "${OTA_APP_NAME}",
  "versionName": "${APP_VERSION}.${APP_BUILD_NUM}",
  "bucketName": "${OSS_BUCKET_NAME}",
  "s3Key": "${TARGET_PATH}",
  "fileName": "${TARGET_PATH}",
  "metaData": "{}"
}
EOF
  )

  #  local body=$(http_post_with_curl "$API_URL" "$TOKEN" "$payload")
  body='{"success":true,"errorCode":null,"message":null,"data":1891}'
  local data
  if command -v jq >/dev/null 2>&1; then
    data=$(echo "$body" | jq -r '.data')
  else
    data=$(echo "$body" | grep -o '"data"[ ]*:[ ]*[^,}]*' | awk -F ':' '{gsub(/ /, "", $2); print $2}')
  fi
  if [[ -z "$data" || "$data" == "null" ]]; then
    echo "ERROR: 获取 data 失败" >&2
    return 1
  fi
  echo "$data"
}

# 获取 accessToken 的方法
get_access_token() {
  local auth_url="http://auth.zelostech.com.cn/app/accessToken"
  local app_id="jenkins"
  local app_key="q1tDXqJhwXDEnSTu4qqWuXBQcTpfRqtZP0i7u2OVoeFRxqFtReWNYQ63k1kduylG"
  local payload="{\"appId\": \"${app_id}\", \"appKey\": \"${app_key}\"}"
  # 使用 http_post_with_curl 发送请求
  # shellcheck disable=SC2155
  local token_response=$(http_post_with_curl "$auth_url" "" "$payload")

  local access_token
  if command -v jq >/dev/null 2>&1; then
    access_token=$(echo "$token_response" | jq -r '.data.token')
  else
    access_token=$(echo "$token_response" | grep -o '"token"[ ]*:[ ]*"[^"]*"' | awk -F '"' '{print $4}')
  fi
  if [[ -z "$access_token" || "$access_token" == "null" ]]; then
    echo "ERROR: 获取 access_token 失败" >&2
    return 1
  fi
  echo "$access_token"
  return $http_status
}

# 获取 accessToken 的方法
get_download_url() {
   local id="$1"
   local url="$DOWNLOAD_URL?id=$id"
   echo  $url
  local body
  body=$(http_post_with_curl "$url" "$TOKEN" "")
  echo $body
  local data
  if command -v jq >/dev/null 2>&1; then
    data=$(echo "$body" | jq -r '.data')
  else
    data=$(echo "$body" | grep -o '"data"[ ]*:[ ]*[^,}]*' | awk -F ':' '{gsub(/ /, "", $2); print $2}')
  fi
  if [[ -z "$data" || "$data" == "null" ]]; then
    echo "ERROR: 获取 data 失败" >&2
    return 1
  fi
  echo "$data"
}

# 在新终端中打开，并忽略exitcode
get_token_without_status() {
  #    local token=$(get_access_token)
  local token="1"
  echo $APP_VERSION
  echo $APP_NAME
  echo $BUILD_TS
  echo $FILE_NAME
  echo token
}
